'use strict';
const { Service } = require('egg');
const data = require('../data/redirect_uri');

class AuthorizeService extends Service {
  matchClientAndUri(client_id, redirect_uri) {
    for (const i in data) {
      if (!data.hasOwnProperty(i)) continue;
      if (data[i].client_id === client_id) {
        if (redirect_uri === undefined) return true;

        const uris = data[i].redirect_uri;
        for (const j in uris) {
          if (!uris.hasOwnProperty(j)) continue;
          if (uris[j] === redirect_uri) return true;
        }
      }
    }
    return false;
  }

  authorizeNeeded(/* client_id */) {
    return true;
  }

  defaultRedirectUri(client_id) {
    for (const i in data) {
      if (!data.hasOwnProperty(i)) continue;
      if (data[i].client_id === client_id) {
        return data[i].redirect_uri[data[i].default];
      }
    }
  }

  description(client_id) {
    for (const i in data) {
      if (!data.hasOwnProperty(i)) continue;
      if (data[i].client_id === client_id) {
        return data[i].description;
      }
    }
  }

  async grant(user, client_id, redirect_uri, scope) {
    const { ctx } = this;
    return await ctx.model.Code.create({
      user,
      client_id,
      redirect_uri,
      scope: JSON.stringify(scope),
      valid: true,
    });
  }
}

module.exports = AuthorizeService;
